import {
  ValidatorConstraint,
  ValidatorConstraintInterface,
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
  length,
} from 'class-validator';

@ValidatorConstraint({ name: 'LengthRw', async: false })
export class MyLength implements ValidatorConstraintInterface {
  validate(value: string, args: ValidationArguments) {
    const [min, max]: number[] = args.constraints;
    // 继承
    if (!length(value, min, max)) {
      return false;
    }

    // 添加额外逻辑
    return value.trim().length >= min;
  }

  defaultMessage(args: ValidationArguments) {
    const [min, max] = args.constraints;
    return `${args.property} 长度必须在 ${min} 到 ${max} 之间且不能全是空格`;
  }
}

export function LengthRw(
  min: number,
  max?: number,
  validationOptions?: ValidationOptions,
) {
  return function (object: object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [min, max],
      validator: MyLength,
    });
  };
}
